package com.luoqy.speedy.config;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import com.luoqy.speedy.data.DataBase;
import com.luoqy.speedy.data.MySqldbUtil;
import com.luoqy.speedy.modular.web.em.FictionEnum;
import com.luoqy.speedy.modular.web.model.Fiction;
import com.luoqy.speedy.modular.web.service.IFictionService;
import com.luoqy.speedy.modular.web.service.UpdateFictionService;
import com.luoqy.speedy.modular.web.service.WriteFictionService;
import com.luoqy.speedy.modular.web.utils.JsoupUtil;

@Configuration
public class UpdateFictionConfig{
    @Resource
    private IFictionService iFictionService;

    @Resource
    private UpdateFictionService updateFictionService;

    @Resource
    private WriteFictionService writeFictionService;
    static int it=1;
    /**
     * 更新有最新章节的小说
     */
    @Scheduled(cron="0 0 */8 * * ?")
    public void updateNewFiction(){
        //获取所有小说
    	List<Fiction> fictionlist=iFictionService.list();
        MySqldbUtil.mysqlExecute("insert into sync_record set name='同步更新小说，共"+fictionlist.size()+"本',time='"+new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date())+"'",new DataBase());
    	ExecutorService service = Executors.newFixedThreadPool(fictionlist.size()/100);
    	 for (Fiction fiction : fictionlist) {
    		service.execute(new Runnable() {
				@Override
				public void run() {
				// TODO Auto-generated method stub
			    	updateFictionService.updateFiction(fiction);
				}    
			});
    	 }
    	 service.shutdown();
    }
    /**
     * 20分钟全量更新未进行全量同步的小说内容
     * fixedDelayString = "1200000"
     */
     //更新时间
    @Scheduled(fixedDelayString = "600000")
    public void update(){
        //获取所有小说
    	Map<String,Object> fictionMap=(Map<String,Object>) MySqldbUtil.mysqlSelect("select * from fiction where isupdate=0 limit 0,1", "none",new DataBase());
        if(null!=fictionMap){
        	Runnable runab=new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					MySqldbUtil.mysqlExecute("insert into sync_record set name='全量更新小说，"+fictionMap.get("fiction_name")+"',time='"+new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date())+"'",new DataBase());
			        //循环更新小说
			        Fiction fiction=new Fiction();
			        fiction.setId(Integer.valueOf(fictionMap.get("id").toString()));
			        fiction.setFictionName(fictionMap.get("fiction_name").toString());
			        fiction.setFictionUrl(fictionMap.get("fiction_url").toString());
			        fiction.setIsupdate(Integer.valueOf(fictionMap.get("isupdate").toString()));
			        updateFictionService.updateFiction(fiction);
			        System.gc();
				}
			};
            new Thread(runab).start();
        }else{
        	System.gc();
        }
    }
    /**
     * 全量更新存储基础信息
     * cron="* * *\\/120 * * ?"
     * */
    @Scheduled(cron="0 0 */120 * * ?")
    public void saveBaseFiction(){
        List<Map<String,Object>> list=(List<Map<String, Object>>) MySqldbUtil.mysqlSelect("select * from collection where open=1", "list",new DataBase());
        ExecutorService service = Executors.newFixedThreadPool(100);
        for (Map<String, Object> map : list) {
        	Runnable runs=new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					String url=map.get("url").toString();
					int page=1;
					boolean flag=false;
					if(url.contains("www.shuquge.com")){
						for (FictionEnum f: FictionEnum.values()){
							do {
					        	url=map.get("url").toString()+f.getIndex()+"_"+page+".html";
					        	Document listPage=JsoupUtil.getDoc(url);
								 Element element = listPage.select("div.l").first();
							     Elements listFictionHtml = element.select("span.s2");
							     if(listFictionHtml.hasText()){
							    	 MySqldbUtil.mysqlExecute("insert into sync_record set name='开始本地增量增加小说信息，更新URL->"+url+"，类型是->"+f.getIndex()+"_"+page+"->"+f.getName()+"',time='"+new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date())+"'",new DataBase());
							         writeFictionService.insertBase(url);
							         page++;
							         flag=true;
							     }else{
							    	 flag=false;
							     }
							     System.gc();
							} while (flag);
				        	page=1;
						}
					}else{
						System.err.println("不支持的链接");
						System.gc();
					}
				}
			};
			service.execute(runs);
		}
        service.shutdown();
    }
}
